import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_terminal_volume_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_oss_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import '../smart_home_upload_service.dart';

/// 创建栏目
class  SmartHomePublishSetVideoCoverPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomePublishSetVideoCoverPage";

  final SmartHomeUploadItemBean videoInfo;

  const SmartHomePublishSetVideoCoverPage(
      {Key key, this.videoInfo,}) : super(key:key);

  @override
  _SmartHomePublishSetVideoCoverPageState createState() => _SmartHomePublishSetVideoCoverPageState();

  static Future<SmartHomeUploadItemBean> navigatorPush(BuildContext context, SmartHomeUploadItemBean videoInfo){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomePublishSetVideoCoverPage(videoInfo: videoInfo,),
        routeName: SmartHomePublishSetVideoCoverPage.ROUTER
    );
  }
}

class _SmartHomePublishSetVideoCoverPageState
    extends BaseState<SmartHomePublishSetVideoCoverPage> {

  SmartHomePublishViewModel _viewModel;

  SmartHomeUploadItemBean _videoInfo;
  int _selectIndex = 0;
  int numberOfThumbnails = 100;
  int quality = 75;
  double _progress = 0;
  VideoPlayerController _videoPlayerController;
  bool _showVideo = false;
  @override
  void initState() {
    super.initState();
    _viewModel = SmartHomePublishViewModel(this);
    _videoInfo = widget?.videoInfo;
    print("duration:" + _videoInfo.videoDuration.toString());
  }

  @override
  void dispose() {
    super.dispose();
    _videoPlayerController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Colors.white,
          body: _toMainColumnWidget(),
        )
    );
  }


  Future<String> generateThumbnail() async {
    final String _videoPath = _videoInfo.getPicOrVideoUrl();
    Duration duration = await _videoPlayerController?.position;
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }
    //文件名
    String defaultName = VgOssUtils.getDefaultFileName(false, imageFormat: "png");

    String path = await VideoThumbnail.thumbnailFile(
      video: _videoPath,
      imageFormat: ImageFormat.PNG,
      quality: quality,
      timeMs: duration.inMilliseconds,
      thumbnailPath: tempDirectory?.path + "/" + defaultName,
    );
    return path;
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        Container(height: 10, color: Color(0XFFF6F7F9),),
        _toSelectedWidget(),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 15),
          alignment: Alignment.centerLeft,
          height: 44,
          child: Text(
            "选择最优的封面后暂停，点击“完成”按钮设置封面",
            style: TextStyle(
                fontSize: 13,
                color: ThemeRepository.getInstance().getCardBgColor_21263C()
            ),
          ),
        ),
        // Container(
        //     height: 56,
        //     child: _toWebPWidget()
        // ),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "选择封面",
      backgroundColor: Color(0XFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toSaveButtonWidget(),
    );
  }

  Widget _toSaveButtonWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      width: 48,
      height: 24,
      unSelectBgColor:Color(0xFFCFD4DB),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.w600),
      selectedTextStyle: TextStyle(
          color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
      text: "完成",
      onTap: ()async{
        loading(true);
        String path = await generateThumbnail();
        FileImage image = FileImage(File(path));
        Map<String, ImageInfo> _imageInfoMap = new Map();
        image.resolve(new ImageConfiguration()).addListener(
            new ImageStreamListener((ImageInfo info, bool _) async {
              _imageInfoMap[path] = info;
              _videoInfo.folderWidth = info.image.width;
              _videoInfo.folderHeight = info.image.height;
              _videoInfo.videoLocalCover = path;
              loading(false);
              RouterUtils.pop(context, result: _videoInfo);
            }));
      },
    );
  }

  ///选中的图片
  Widget _toSelectedWidget(){
    return Container(
      height: 470,
      width: ScreenUtils.screenW(context),
      padding: EdgeInsets.only(left: 15, right: 15, top: 10),
      color: Color(0XFFF6F7F9),
      child: Opacity(
        opacity: _showVideo?1:0,
        child: Container(
          child: Center(
            child: VideoWidget(
              videoInfo: new PhotoPreviewInfoVo(
                url: _videoInfo.getPicOrVideoUrl(),
                type: PhotoPreviewType.video,
                loadingCoverUrl:VgPhotoPreview.getImageQualityStr(_videoInfo?.getLocalPicUrl(), null),
              ),
              videoMargin: EdgeInsets.only(bottom: 0),
              onPlayerControllerCreated:(controller){
                  _videoPlayerController = controller;
                  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                    Future.delayed(new Duration(milliseconds: 500),(){
                      setState(() {
                        _showVideo = true;
                      });
                    });
                  });
              },
              autoPlay: false,
              autoInitialize: true,
              looping: false,
              showControls: true,
              allowMuting: false,
              allowFullScreen: false,
            ),
          ),
        ),
      ),
    );

  }

  Widget _toSelectedCoverWidget(){
    return Center(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: VgCacheNetWorkImage(
          _videoInfo?.getLocalPicUrl(),
          fit: BoxFit.contain,
        ),
      ),
    );

    // StreamBuilder<Uint8List>(
    //   stream: generateThumbnail(),
    //   builder: (context, snapshot){
    //     if(snapshot.hasData){
    //       Uint8List _imageBytes = snapshot.data;
    //       return Center(
    //         child: ClipRRect(
    //           borderRadius: BorderRadius.circular(4),
    //           child: Image(
    //             image: MemoryImage(_imageBytes),
    //             fit: BoxFit.contain,
    //           ),
    //         ),
    //       );
    //     }else{
    //       return Container(
    //         color: Colors.grey[900],
    //         height: 56,
    //         width: double.maxFinite,
    //       );
    //     }
    //   },
    // )
  }

  Widget _toSeekBarWidget(){
    return SliderTheme(
      data: SliderThemeData(
          overlayShape: SliderComponentShape.noOverlay,
          thumbShape: RingThumbShape(15, 25, 12.5, 10),
          trackHeight: 4,
          trackShape: CustomRoundedRectSliderTrackShape(),
          inactiveTickMarkColor: Colors.transparent,
          activeTickMarkColor: Colors.transparent,
          inactiveTrackColor: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
          activeTrackColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          valueIndicatorColor: Colors.transparent),
      child: Slider(
        min: 0.0,
        max: (_videoInfo?.videoDuration??0)*1000.0,
        value: _progress,
        divisions: 1000,
        onChanged: (value) {
          _videoPlayerController?.seekTo(Duration(milliseconds: value.ceil()));
          setState(() {
            this._progress = value;
          });
        },
        onChangeEnd: (value){

        },
      ),
    );
  }

  ///图片列表
  // Widget _toWebPWidget(){
  //   return StreamBuilder<Uint8List>(
  //     stream: generateThumbnail(),
  //     builder: (context, snapshot){
  //       if(snapshot.hasData){
  //         Uint8List _imageBytes = snapshot.data;
  //         return SizedBox(
  //           height: 48,
  //           width: 48,
  //           child: Image(
  //             image: MemoryImage(_imageBytes),
  //             fit: BoxFit.cover,
  //           ),
  //         );
  //       }else{
  //         return Container(
  //           color: Colors.grey[900],
  //           height: 56,
  //           width: double.maxFinite,
  //         );
  //       }
  //     },
  //   );
  // }

  // ///图片列表
  // Widget _toImageListWidget(){
  //   return StreamBuilder<List<Uint8List>>(
  //     stream: generateThumbnail(),
  //     builder: (context, snapshot){
  //       if(snapshot.hasData){
  //         List<Uint8List> _imageBytes = snapshot.data;
  //         return ListView.builder(
  //             scrollDirection: Axis.horizontal,
  //             itemCount: _imageBytes.length,
  //             itemBuilder: (context, index) {
  //               return SizedBox(
  //                 height: 48,
  //                 width: 48,
  //                 child: Image(
  //                   image: MemoryImage(_imageBytes[index]),
  //                   fit: BoxFit.cover,
  //                 ),
  //               );
  //             });
  //       }else{
  //         return Container(
  //           color: Colors.grey[900],
  //           height: 56,
  //           width: double.maxFinite,
  //         );
  //       }
  //     },
  //   );
  // }

  Widget _toListItemWidget(int index, SmartHomeUploadItemBean item){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){


      },
      child: Container(
        width: (index == _selectIndex)?56:48,
        height: (index == _selectIndex)?56:48,
        alignment: Alignment.center,
        foregroundDecoration: BoxDecoration(
            border: Border.all(
                color: (index == _selectIndex)?ThemeRepository.getInstance().getPrimaryColor_1890FF():Colors.transparent,
                width: (index == _selectIndex)? 2:0),
            borderRadius: BorderRadius.circular(4),
            color: Colors.transparent
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(color: Colors.black),
            child: VgCacheNetWorkImage(
              item?.getPicOrVideoUrl() ?? "",
              fit: BoxFit.cover,
              imageQualityType: ImageQualityType.middleDown,
            ),
          ),
        ),
      ),
    );
  }



}
